'use strict';

const { logger } = require('ee-core/log');
const { getConfig } = require('ee-core/config');
const { getMainWindow } = require('ee-core/electron');
const {screen} = require('electron');

class Lifecycle {

  /**
   * core app have been loaded
   */
  async ready() {
    logger.info('[lifecycle] ready');
  }

  /**
   * electron app ready
   */
  async electronAppReady() {
    logger.info('[lifecycle] electron-app-ready');
  }

  /**
   * main window have been loaded
   */
  async windowReady() {
    logger.info('[lifecycle] window-ready');
    // 延迟加载，无白屏
    const { windowsOption } = getConfig();
    if (windowsOption.show == false) {
      const win = getMainWindow();
      win.once('ready-to-show', () => {
        win.show();
        win.focus();
      })
    }
    logger.info('======');
    // 监听来自渲染进程的消息
    // getMainWindow().webContents.on('mouse-leave', () => {
    //   logger.info('[lifecycle] mouse-leave');
    // });

    let mainWindow = getMainWindow();
    // 设置一个监听器，拖动窗口到右侧时隐藏
    let isWindowHidden = false;
    // 每帧检测窗口位置
    setInterval(() => {
      const bounds = mainWindow.getBounds();
      const rightEdge = screen.getPrimaryDisplay().workArea.width;
// console.log("----"+rightEdge+"-"+bounds.x+"-"+isWindowHidden);
      // 如果窗口靠近右边缘（距离屏幕右侧10px以内），隐藏窗口
      if (rightEdge - bounds.x <= 500 && !isWindowHidden) {
        console.log("隐藏")
        mainWindow.setBounds({
          x: rightEdge - 5, // 留出5px边界
          y: bounds.y,
          width: 5, // 窗口宽度为5px，几乎不可见
          height: bounds.height
        });
        mainWindow.setPosition(1490,30)
        isWindowHidden = true;
      }
      // 如果鼠标接触到边界，重新展开窗口
      const mousePos = screen.getCursorScreenPoint();
      if (isWindowHidden && mousePos.x > rightEdge - 10) {
        mainWindow.setBounds({
          x: rightEdge - 300, // 展开到原来的宽度
          y: bounds.y,
          width: 300,
          height: bounds.height
        });
        isWindowHidden = false;
      }
    }, 100);  // 每100ms检查一次
  }

  /**
   * before app close
   */  
  async beforeClose() {
    logger.info('[lifecycle] before-close');
  }
}
Lifecycle.toString = () => '[class Lifecycle]';

module.exports = {
  Lifecycle
};